<?php

declare(strict_types=1);


namespace app\controller\mini;

use app\controller\admin\AdminBaseController;
use app\model\admin\Product;
use app\model\admin\ProductAttrResult;
use app\model\admin\ProductAttrValue;
use app\Request;
use app\model\admin\SysMember;
use app\model\mini\Cart;
use app\model\mini\MiniUser;
use app\model\mini\OrderItem;
use app\model\mini\OrderLog;
use app\model\mini\RefundOrder;
use app\service\JwtAuth;
use think\facade\Db;

class RefundController extends AdminBaseController
{
    public function refundResonList(Request $request)
    {
        $data = [
            "收货地址填错了",
            "与描述不符",
            "信息填错了，重新拍",
            "收到商品损坏了",
            "未按预定时间发货",
            "其它原因",
        ];
        return success($data);
    }
    public function getRefundInfo(Request $request)
    {
        $id = input('id');
        $user_id = $request->user_id;
        $info = OrderItem::with(['order'])->where('user_id', $user_id)->find($id);
        return success($info);
    }
    // 申请退款
    public function applyRefund(Request $request)
    {
        // return;
        $user_id = $request->user_id;
        $params = $request->param();
        $info = OrderItem::with(['order'])->where([
            'user_id' => $user_id
        ])->find($params['id']);
        // if ($info->refund_status != 0 || $info->refund_status != 3) {
        //     return error('当前订单不允许退款');
        // }
        if (!in_array($info->refund_status, [0, 3])) {
            return error('当前订单不允许退款');
        }
        $refund_type = $params['refund_type'] ?? 1;
        // //  将订单拆分
        // $info->refund_status = 1;
        // $info->save();
        Db::transaction(function () use ($params, $info, $refund_type, $user_id) {
            // 是否发货
            if ($info->order->order_status == 0) {
                // 当前包裹待发货
                $refund_type = 1; //只需要仅退款
            }
            $refund_price = $params['refund_num'] * $info->goods_price;
            Db::table('user_order_item')->where('id', $info->id)->update([
                "refund_status" => 1, //申请中
                "refund_type" => $refund_type,
                // todo
                "refund_num" => $params['refund_num'],
                "refund_price" => $refund_price
            ]);
            // $refund_price = $info->goods_price * $info->goods_num;
            $data = [
                "order_id" => $info->order->id,
                "user_id" => $user_id,
                "order_sn" => $info->order->order_sn,
                "refund_type" => $refund_type,
                "refund_reson" => $params['reson'],
                "refund_price" => $refund_price,
                "order_item_id" => $info->id,
                "refund_remark" => $params['remark'],
                "refund_img" => $params['img'] ?? "",
                "goods_info" => json_encode($info->good_info),
            ];
            if ($info->spec_type == 1) {
                $data['sku_info'] = json_encode($info->sku);
            }

            RefundOrder::create($data);
            if ($refund_type == 1) {
                OrderLog::create([
                    "order_id" => $info->order_id,
                    "order_item_id" => $info->id,
                    "message" => "用户申请仅退款"
                ]);
            } else {
                OrderLog::create([
                    "order_id" => $info->order_id,
                    "order_item_id" => $info->id,
                    "message" => "用户申请退货退款"
                ]);
            }
        });

        return success();
    }
    // 
    public function getRefundList(Request $request)
    {
        $type = input('type');
        $user_id = $request->user_id;
        if ($type == 1) {
            // 全部
            $list = OrderItem::with(['order'])->where([
                "user_id" => $user_id,
            ])->where('refund_status', "<>", 0)->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        }
        if ($type == 2) {
            // 申请中
            $list =  OrderItem::with(['order'])->where([
                "user_id" => $user_id,
                "refund_status" => 1,
            ])->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        }
        if ($type == 3) {
            // 已退款
            $list = OrderItem::with(['order'])->where([
                "user_id" => $user_id,
                "refund_status" => 2,
            ])->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        }

        return successPage($list);
    }
    public function refundDetail(Request $request)
    {
        $orderItemId = input('orderItemId');
        $user_id = $request->user_id;
        $info = OrderItem::with(['refund' => function ($q) {
            $q->where('is_del', '<>', 1)->order('id', 'desc'); //查询未删除的订单
        }])->where([
            "user_id" => $user_id,
        ])->where('refund_status', '<>', 0)->find($orderItemId);
        $info->total_price = number_format(($info->goods_price * $info->goods_num), 2);
        return success($info);
    }
    public function canelApply(Request $request)
    {
        $orderItemId = input('orderItemId');
        $user_id = $request->user_id;
        $info = OrderItem::with(['refund'])->where([
            "user_id" => $user_id,
            "refund_status" => 1,
        ])->find($orderItemId);
        if ($info) {
            // $info->refund_status
            Db::transaction(function () use ($info) {
                Db::table('user_order_item')->where([
                    'id' => $info->id
                ])->update([
                    "refund_status" => 0,
                    "updated_at" => time()
                ]);
                Db::table('user_refund')->where([
                    "order_item_id" => $info->id,
                ])->update([
                    "is_cancel" => 1,
                    "is_del" => 1,
                    "updated_at" => time()
                ]);
                OrderLog::create([
                    "order_id" => $info->order_id,
                    "order_item_id" => $info->id,
                    "message" => "用户主动取消退款"
                ]);
            });
            return success();
        } else {
            return error('取消失败');
        }
    }
    // 用户填写退款单
    public function userSubmitExpress(Request $request)
    {
        $params = $request->param();
        $user_id = $request->user_id;
        $info = OrderItem::with(['order', 'refund'])->where([
            'user_id' => $user_id,
            "refund_status" => 5
        ])->find($params['id']);
        if (!$info) {
            return error('记录不存在');
        }
        Db::transaction(function () use ($info, $params) {
            Db::table('user_order_item')->where('id', $params['id'])->update([
                "refund_status" => 6, //修改为待商家收货
                'refund_express' => $params['express_no'],
                "refund_remark" => $params['remark'] ?? "",
                "refund_reason_wap_img" => $params['img'] ?? ""
            ]);
            Db::table('user_refund')->where('id', $info->refund->id)->update([
                "refund_express" => $params['express_no'],
                "user_express_remark" => $params['remark'] ?? null,
                "user_express_img" => $params['img'] ?? null,
            ]);
            OrderLog::create([
                "order_id" => $info->order->id,
                "order_item_id" => $params['id'],
                "message" => "用户已填写快递单号"
            ]);
        });
        return success();
    }
}
